<template>
  <el-drawer
    v-model="localDrawer"
    direction="rtl"
    @close="handleClose"
    @open="handleOpen"
    append-to-body
    destroy-on-close
  >
    <template #header>
      <h4 v-if="localType === 'add'" class="text-lg font-bold">添加学生</h4>
      <h4 v-if="localType === 'edit'" class="text-lg font-bold">修改学生</h4>
      <h4 v-if="localType === 'delete'" class="text-lg font-bold">删除学生</h4>
    </template>
    <template #default>
      <div v-loading="loading">
        <el-result
            v-if="localType === 'edit'"
            icon="warning"
            title="在下方修改这个学生"
        >
        </el-result>
        <el-result
            v-if="localType === 'delete'"
            icon="error"
            title="确认吗"
            sub-title="请确认是否删除该学生？"
        >
        </el-result>
        <template
            v-for="[key, value] in Object.entries(localItemData)"
            :key="key"
        >
          <div v-if="displayFields.includes(key)" class="pb-4">
            <label class="font-bold text-base text-gray-400">{{
                getLabel(key)
              }}</label>
            <div
                v-if="localType !== 'edit' && localType !== 'add'"
                class="h-12 w-full mt-2"
            >
              <el-input
                  v-model="localItemData[key]"
                  class="h-12 w-full mt-2"
                  disabled
              ></el-input>
            </div>
            <template v-else>
              <el-select
                  v-if="key === 'sNumtype'"
                  class="mt-2"
                  v-model="localItemData[key]"
                  placeholder="请选择"
              >
                <el-option
                    v-for="item in sNumtypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <el-select
                  v-else-if="key === 'sSex'"
                  class="mt-2"
                  v-model="localItemData[key]"
                  placeholder="请选择"
              >
                <el-option
                    v-for="item in sSexOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <el-date-picker
                  v-else-if="key === 'sBirth'"
                  class="w-full"
                  v-model="localItemData[key]"
                  type="date"
                  placeholder="Pick a day"
                  :disabled-date="disabledDate"
              />
              <el-input
                  v-else
                  v-model="localItemData[key]"
                  class="mt-2"
              ></el-input>
            </template>
          </div>
        </template>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button :disabled="loading" @click="cancelClick">取消</el-button>
        <el-button :disabled="loading" type="primary" @click="confirmClick">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, watch } from "vue";
import { ApiUser } from "@/core/api/index.js";
import Swal from "sweetalert2";
import _ from "lodash";

const loading = ref(false);
const props = defineProps({
  drawer: {
    type: Boolean,
    required: true,
  },
  itemData: {
    type: Object,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
});
const emit = defineEmits(["update:drawer", "refresh-list"]);
const localDrawer = ref(props.drawer);
const localItemData = ref(props.itemData);
const localType = ref(props.type);

watch(
  () => props.drawer,
  (newVal) => {
    localDrawer.value = newVal;
  }
);

watch(
  () => props.itemData,
  (newVal) => {
    localItemData.value = _.cloneDeep(newVal);
  },
  { deep: true }
);

watch(
  () => props.type,
  (newVal) => {
    localType.value = newVal;
  }
);

const handleClose = () => {
  emit("update:drawer", false);
};

const getLabel = (field) => {
  const labels = {
    sId: "学生学号",
    rNumber: "楼栋号",
    dNumber: "宿舍号",
    sName: "学生姓名",
    sPassword: "学生密码",
    sSex: "性别",
    stel: "手机号码",
    sAddress: "家庭住址",
    sNumber: "证件号码",
    sNumtype: "证件类型",
    sBirth: "出生日期",
    sClass: "班级",
    sMajor: "专业名称",
  };
  return labels[field];
};

const displayFields = [
  "sId",
  "rNumber",
  "dNumber",
  "sName",
  "sPassword",
  "sSex",
  "stel",
  "sAddress",
  "sNumber",
  "sNumtype",
  "sBirth",
  "sClass",
  "sMajor",
];

const sNumtypeOptions = [
  {
    value: "居民身份证",
    label: "居民身份证",
  },
  {
    value: "港澳台通行证",
    label: "港澳台通行证",
  },
];

const sSexOptions = [
  {
    value: "M",
    label: "男",
  },
  {
    value: "F",
    label: "女",
  },
];

const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

const cancelClick = () => {
  emit("update:drawer", false);
};

const confirmClick = () => {
  if (localType.value === "add") {
    addStudent();
  }
  if (localType.value === "edit") {
    editStudent();
  }
  if (localType.value === "delete") {
    deleteStudent();
  }
};

const addStudent = async () => {
  loading.value = true;
  const response = await ApiUser.addStudent({
    dNumber: localItemData.value.dNumber,
    rNumber: localItemData.value.rNumber,
    sAddress: localItemData.value.sAddress,
    sBirth: localItemData.value.sBirth,
    sClass: localItemData.value.sClass,
    sId: localItemData.value.sId,
    sMajor: localItemData.value.sMajor,
    sName: localItemData.value.sName,
    sNumber: localItemData.value.sNumber,
    sNumtype: localItemData.value.sNumtype,
    sPassword: localItemData.value.sPassword,
    sSex: localItemData.value.sSex,
    sTel: localItemData.value.stel,
  });
  if (response.code == 0) {
    Swal.fire({
      title: "成功添加学生",
      text: `您已成功添加学生：${localItemData.value.sName}`,
      icon: "success",
    });
    emit("refresh-list");
  }
  loading.value = false;
  emit("update:drawer", false);
};

const editStudent = async () => {
  loading.value = true;
  const response = await ApiUser.editStudent({
    sId: localItemData.value.sId,
    rNumber: localItemData.value.rNumber,
    dNumber: localItemData.value.dNumber,
    sName: localItemData.value.sName,
    sPassword: localItemData.value.sPassword,
    sSex: localItemData.value.sSex,
    sTel: localItemData.value.stel,
    sAddress: localItemData.value.sAddress,
    sNumber: localItemData.value.sNumber,
    sNumtype: localItemData.value.sNumtype,
    sBirth: localItemData.value.sBirth,
    sClass: localItemData.value.sClass,
    sMajor: localItemData.value.sMajor,
  });
  if (response.code == 0) {
    Swal.fire({
      title: "成功修改学生",
      text: `您已成功修改学生：${localItemData.value.sName}`,
      icon: "success",
    });
    emit("refresh-list");
  }
  loading.value = false;
  emit("update:drawer", false);
};

const deleteStudent = async () => {
  loading.value = true;
  const response = await ApiUser.deleteStudent({
    studentId: localItemData.value.sId,
  });
  if (response.code == 0) {
    Swal.fire({
      title: "成功删除学生",
      text: `您已成功删除学生：${localItemData.value.sName}`,
      icon: "success",
    });
    emit("refresh-list");
  }
  loading.value = false;
  emit("update:drawer", false);
};
</script>
